import React, { useState } from 'react';
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
import { Button } from './Button';

interface PaginationProps {
  currentPage: number;
  totalPages: number;
  totalItems: number;
  onPageChange: (page: number) => void;
  pageSize?: number;
  showPageSizeSelector?: boolean;
  onPageSizeChange?: (size: number) => void;
  className?: string;
}

export const Pagination: React.FC<PaginationProps> = ({
  currentPage,
  totalPages,
  totalItems,
  onPageChange,
  pageSize = 10,
  showPageSizeSelector = false,
  onPageSizeChange,
  className = ''
}) => {
  const [inputPage, setInputPage] = useState('');
  
  // 如果总页数小于等于1，不显示分页
  if (totalPages <= 1) {
    return null;
  }

  // 处理页码输入跳转
  const handlePageJump = () => {
    const page = parseInt(inputPage);
    if (page >= 1 && page <= totalPages) {
      onPageChange(page);
      setInputPage('');
    }
  };

  // 处理输入框回车事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handlePageJump();
    }
  };

  // 生成页码数组
  const generatePageNumbers = () => {
    const pages = [];
    const maxVisiblePages = 5;
    
    if (totalPages <= maxVisiblePages) {
      // 如果总页数较少，显示所有页码
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      // 如果总页数较多，智能显示页码
      if (currentPage <= 3) {
        // 当前页在前面
        for (let i = 1; i <= 4; i++) {
          pages.push(i);
        }
        pages.push('...');
        pages.push(totalPages);
      } else if (currentPage >= totalPages - 2) {
        // 当前页在后面
        pages.push(1);
        pages.push('...');
        for (let i = totalPages - 3; i <= totalPages; i++) {
          pages.push(i);
        }
      } else {
        // 当前页在中间
        pages.push(1);
        pages.push('...');
        for (let i = currentPage - 1; i <= currentPage + 1; i++) {
          pages.push(i);
        }
        pages.push('...');
        pages.push(totalPages);
      }
    }
    
    return pages;
  };

  const pageNumbers = generatePageNumbers();
  const pageSizeOptions = [10, 20, 50, 100];

  return (
    <div className={`flex items-center justify-between ${className}`}>
      {/* 左侧：记录信息 */}
      <div className="flex items-center space-x-4">
        <p className="text-sm text-gray-600">
          共 {totalItems} 条记录，第 {currentPage} / {totalPages} 页
        </p>
        
        {/* 页面大小选择器 */}
        {showPageSizeSelector && onPageSizeChange && (
          <div className="flex items-center space-x-2">
            <span className="text-sm text-gray-600">每页显示</span>
            <select
              value={pageSize}
              onChange={(e) => onPageSizeChange(parseInt(e.target.value))}
              className="px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            >
              {pageSizeOptions.map(size => (
                <option key={size} value={size}>{size}</option>
              ))}
            </select>
            <span className="text-sm text-gray-600">条</span>
          </div>
        )}
      </div>

      {/* 右侧：分页控件 */}
      <div className="flex items-center space-x-2">
        {/* 首页按钮 */}
        <Button
          variant="outline"
          size="sm"
          disabled={currentPage === 1}
          onClick={() => onPageChange(1)}
          icon={<ChevronsLeft className="w-4 h-4" />}
          className="text-gray-600"
        >
          首页
        </Button>

        {/* 上一页按钮 */}
        <Button
          variant="outline"
          size="sm"
          disabled={currentPage === 1}
          onClick={() => onPageChange(currentPage - 1)}
          className="text-gray-600"
        >
          上一页
        </Button>

        {/* 页码按钮 */}
        <div className="flex items-center space-x-1">
          {pageNumbers.map((page, index) => (
            <React.Fragment key={index}>
              {page === '...' ? (
                <span className="px-2 py-1 text-gray-400">...</span>
              ) : (
                <Button
                  variant={page === currentPage ? "primary" : "outline"}
                  size="sm"
                  onClick={() => onPageChange(page as number)}
                  className={`min-w-[32px] ${
                    page === currentPage 
                      ? 'bg-primary-500 text-white border-primary-500' 
                      : 'text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  {page}
                </Button>
              )}
            </React.Fragment>
          ))}
        </div>

        {/* 下一页按钮 */}
        <Button
          variant="outline"
          size="sm"
          disabled={currentPage === totalPages}
          onClick={() => onPageChange(currentPage + 1)}
          className="text-gray-600"
        >
          下一页
        </Button>

        {/* 末页按钮 */}
        <Button
          variant="outline"
          size="sm"
          disabled={currentPage === totalPages}
          onClick={() => onPageChange(totalPages)}
          icon={<ChevronsRight className="w-4 h-4" />}
          className="text-gray-600"
        >
          末页
        </Button>

        {/* 页码跳转输入框 */}
        <div className="flex items-center space-x-2 ml-4">
          <span className="text-sm text-gray-600">跳转至</span>
          <input
            type="number"
            min="1"
            max={totalPages}
            value={inputPage}
            onChange={(e) => setInputPage(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="页码"
            className="w-16 px-2 py-1 border border-gray-300 rounded text-sm text-center focus:ring-2 focus:ring-primary-500 focus:border-transparent"
          />
          <Button
            variant="outline"
            size="sm"
            onClick={handlePageJump}
            disabled={!inputPage || parseInt(inputPage) < 1 || parseInt(inputPage) > totalPages}
            className="text-gray-600"
          >
            跳转
          </Button>
        </div>
      </div>
    </div>
  );
}; 